package com.asset.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.springframework.util.StringUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * @author zxm
 * 
 */
public class CodeCreator {
	private static final String CHARSET = "utf-8";
	// LOGO宽度
	private static final int WIDTH = 200;
	// LOGO高度
	private static final int HEIGHT = 200;

	private static final float logoRatio = 0.28f;
	private static final int fontSize = 14;
	private static final String format = "JPG";
	private static int BLACK = 0x000000;
	private static int WHITE = 0xFFFFFF;

	public static int[] bottomStart;// 二维码最下边的开始坐标
	public static int[] bottomEnd;// 二维码最下边的结束坐标

	private static BufferedImage createCodeImage(String context) {

		Map<EncodeHintType, Object> hint = new HashMap<>();
		hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hint.put(EncodeHintType.CHARACTER_SET, CHARSET);
		hint.put(EncodeHintType.MARGIN, 1);
		MultiFormatWriter writer = new MultiFormatWriter();
		BufferedImage img = null;
		try {
			BitMatrix bm = writer.encode(context, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hint);
			int[] locationTopLeft = bm.getTopLeftOnBit();
			int[] locationBottomRight = bm.getBottomRightOnBit();
			bottomStart = new int[] { locationTopLeft[0], locationBottomRight[1] };
			bottomEnd = locationBottomRight;
			int w = bm.getWidth();
			int h = bm.getHeight();
			img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
			for (int x = 0; x < w; x++) {
				for (int y = 0; y < h; y++) {
					img.setRGB(x, y, bm.get(x, y) ? BLACK : WHITE);
				}
			}
		} catch (WriterException e) {
			e.printStackTrace();
		}
		return img;
	}

	public static void createCodeImage(String context, String logoPath, String desc, OutputStream output) {
		BufferedImage bm = createCodeImage(context);
		if(logoPath != null){
			File logoFile = new File(logoPath);
			try {			
				BufferedImage logoImg;
				logoImg = ImageIO.read(logoFile);
				int logoWidth = logoImg.getWidth();
				int logoHeight = logoImg.getHeight();
				int width = bm.getWidth();
				int height = bm.getHeight();
				if (logoRatio > 0) {
					logoWidth = logoWidth > width * logoRatio ? (int) (width * logoRatio) : logoWidth;
					logoHeight = logoHeight > height * logoRatio ? (int) (height * logoRatio) : logoHeight;
				}
				int x = (width - logoWidth) / 2;
				int y = (height - logoHeight) / 2;
				Graphics g = bm.getGraphics();
				g.drawImage(logoImg, x, y, logoWidth, logoHeight, null);
				// 得到白边需要的内容
				if (!StringUtils.isEmpty(desc)) {
					int whiteWidth = HEIGHT - bottomEnd[1];
					Font font = new Font("黑体", Font.TYPE1_FONT, fontSize);
					int fontHeight = g.getFontMetrics(font).getHeight();
					// 计算需要多少行
					int lineNum = 1;
					int currentLineLen = 0;
					for (int i = 0; i < desc.length(); i++) {
						char c = desc.charAt(i);
						int charWidth = g.getFontMetrics(font).charWidth(c);
						if (currentLineLen + charWidth > width) {
							lineNum++;
							currentLineLen = 0;
							continue;
						}
						currentLineLen += charWidth;
					}
					int totalFontHeight = fontHeight * lineNum;
					int wordTopMargin = 4;
					BufferedImage bm1 = new BufferedImage(width, height + totalFontHeight + wordTopMargin - whiteWidth,
							BufferedImage.TYPE_INT_RGB);
					Graphics g1 = bm1.getGraphics();
					if (totalFontHeight + wordTopMargin - whiteWidth > 0) {
						// 外围白边的颜色
						g1.setColor(Color.white);
						g1.fillRect(0, height, width, totalFontHeight + wordTopMargin - whiteWidth);
					}
					g1.setColor(new Color(BLACK));
					g1.setFont(font);
					g1.drawImage(bm, 0, 0, null);
					width = bottomEnd[0] - bottomStart[0];
					height = bottomEnd[1] + 1;
					currentLineLen = 0;
					int currentLineIndex = 0;
					int baseLo = g1.getFontMetrics().getAscent();
					for (int i = 0; i < desc.length(); i++) {
						String c = desc.substring(i, i + 1);
						int charWidth = g.getFontMetrics(font).stringWidth(c);
						if (currentLineLen + charWidth > width) {
							currentLineIndex++;
							currentLineLen = 0;
							g1.drawString(c, currentLineLen + whiteWidth,
									height + baseLo + fontHeight * (currentLineIndex) + wordTopMargin);
							currentLineLen = charWidth;
							continue;
						}
						g1.drawString(c, currentLineLen + whiteWidth,
								height + baseLo + fontHeight * (currentLineIndex) + wordTopMargin);
						currentLineLen += charWidth;
					}
					g1.dispose();
					bm = bm1;
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}else{
			if (!StringUtils.isEmpty(desc)) {
				Graphics g = bm.getGraphics();
				int width = bm.getWidth();
				int height = bm.getHeight();
				int whiteWidth = HEIGHT - bottomEnd[1];
				Font font = new Font("黑体", Font.TYPE1_FONT, fontSize);
				int fontHeight = g.getFontMetrics(font).getHeight();
				// 计算需要多少行
				int lineNum = 1;
				int currentLineLen = 0;
				for (int i = 0; i < desc.length(); i++) {
					char c = desc.charAt(i);
					int charWidth = g.getFontMetrics(font).charWidth(c);
					if (currentLineLen + charWidth > width) {
						lineNum++;
						currentLineLen = 0;
						continue;
					}
					currentLineLen += charWidth;
				}
				int totalFontHeight = fontHeight * lineNum;
				int wordTopMargin = 4;
				BufferedImage bm1 = new BufferedImage(width, height + totalFontHeight + wordTopMargin - whiteWidth,
						BufferedImage.TYPE_INT_RGB);
				Graphics g1 = bm1.getGraphics();
				if (totalFontHeight + wordTopMargin - whiteWidth > 0) {
					// 外围白边的颜色
					g1.setColor(Color.white);
					g1.fillRect(0, height, width, totalFontHeight + wordTopMargin - whiteWidth);
				}
				g1.setColor(new Color(BLACK));
				g1.setFont(font);
				g1.drawImage(bm, 0, 0, null);
				width = bottomEnd[0] - bottomStart[0];
				height = bottomEnd[1] + 1;
				currentLineLen = 0;
				int currentLineIndex = 0;
				int baseLo = g1.getFontMetrics().getAscent();
				for (int i = 0; i < desc.length(); i++) {
					String c = desc.substring(i, i + 1);
					int charWidth = g.getFontMetrics(font).stringWidth(c);
					if (currentLineLen + charWidth > width) {
						currentLineIndex++;
						currentLineLen = 0;
						g1.drawString(c, currentLineLen + whiteWidth,
								height + baseLo + fontHeight * (currentLineIndex) + wordTopMargin);
						currentLineLen = charWidth;
						continue;
					}
					g1.drawString(c, currentLineLen + whiteWidth,
							height + baseLo + fontHeight * (currentLineIndex) + wordTopMargin);
					currentLineLen += charWidth;
				}
				g1.dispose();
				bm = bm1;
		}
			
		}
		
		
		/*File logoFile = new File(logoPath);
		try {			
			BufferedImage logoImg;
			logoImg = ImageIO.read(logoFile);
			int logoWidth = logoImg.getWidth();
			int logoHeight = logoImg.getHeight();
			int width = bm.getWidth();
			int height = bm.getHeight();
			if (logoRatio > 0) {
				logoWidth = logoWidth > width * logoRatio ? (int) (width * logoRatio) : logoWidth;
				logoHeight = logoHeight > height * logoRatio ? (int) (height * logoRatio) : logoHeight;
			}
			int x = (width - logoWidth) / 2;
			int y = (height - logoHeight) / 2;
			Graphics g = bm.getGraphics();
			g.drawImage(logoImg, x, y, logoWidth, logoHeight, null);
			// 得到白边需要的内容
			if (!StringUtils.isEmpty(desc)) {
				int whiteWidth = HEIGHT - bottomEnd[1];
				Font font = new Font("黑体", Font.TYPE1_FONT, fontSize);
				int fontHeight = g.getFontMetrics(font).getHeight();
				// 计算需要多少行
				int lineNum = 1;
				int currentLineLen = 0;
				for (int i = 0; i < desc.length(); i++) {
					char c = desc.charAt(i);
					int charWidth = g.getFontMetrics(font).charWidth(c);
					if (currentLineLen + charWidth > width) {
						lineNum++;
						currentLineLen = 0;
						continue;
					}
					currentLineLen += charWidth;
				}
				int totalFontHeight = fontHeight * lineNum;
				int wordTopMargin = 4;
				BufferedImage bm1 = new BufferedImage(width, height + totalFontHeight + wordTopMargin - whiteWidth,
						BufferedImage.TYPE_INT_RGB);
				Graphics g1 = bm1.getGraphics();
				if (totalFontHeight + wordTopMargin - whiteWidth > 0) {
					// 外围白边的颜色
					g1.setColor(Color.white);
					g1.fillRect(0, height, width, totalFontHeight + wordTopMargin - whiteWidth);
				}
				g1.setColor(new Color(BLACK));
				g1.setFont(font);
				g1.drawImage(bm, 0, 0, null);
				width = bottomEnd[0] - bottomStart[0];
				height = bottomEnd[1] + 1;
				currentLineLen = 0;
				int currentLineIndex = 0;
				int baseLo = g1.getFontMetrics().getAscent();
				for (int i = 0; i < desc.length(); i++) {
					String c = desc.substring(i, i + 1);
					int charWidth = g.getFontMetrics(font).stringWidth(c);
					if (currentLineLen + charWidth > width) {
						currentLineIndex++;
						currentLineLen = 0;
						g1.drawString(c, currentLineLen + whiteWidth,
								height + baseLo + fontHeight * (currentLineIndex) + wordTopMargin);
						currentLineLen = charWidth;
						continue;
					}
					g1.drawString(c, currentLineLen + whiteWidth,
							height + baseLo + fontHeight * (currentLineIndex) + wordTopMargin);
					currentLineLen += charWidth;
				}
				g1.dispose();
				bm = bm1;
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
*/
		try {
			ImageIO.write(bm, format, output);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void createCodeImage(String context, String logoPath, String desc, File file) {
		File parent = file.getParentFile();
		if (!parent.exists())
			parent.mkdirs();
		OutputStream output = null;
		try {
			output = new BufferedOutputStream(new FileOutputStream(file));
			createCodeImage(context, logoPath, desc, output);
			output.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void createCodeImage(String context, String logoPath, String desc, String filePath) {
		createCodeImage(context, logoPath, desc, new File(filePath));
	}

	public static void main(String[] args) throws Exception {
		 

		createCodeImage("http://www.chinac.com", null, "资产编号:",
				"C:/Users/Administrator/Desktop/LT.JPG");
	}
}